// 首页功能
class Dashboard {
    constructor() {
        this.currentDate = new Date();
        this.selectedDate = null;
        this.timerInterval = null;
        this.timerMinutes = 25;
        this.timerSeconds = 0;
        this.timerRunning = false;
        this.timerPaused = false;
        
        this.init();
    }
    
    init() {
        this.initCalendar();
        this.initTimer();
        this.bindEvents();
    }
    
    // 初始化日历
    initCalendar() {
        this.updateCalendar();
    }
    
    // 更新日历显示
    updateCalendar() {
        const year = this.currentDate.getFullYear();
        const month = this.currentDate.getMonth();
        
        // 更新月份年份显示
        const monthNames = ["一月", "二月", "三月", "四月", "五月", "六月",
                          "七月", "八月", "九月", "十月", "十一月", "十二月"];
        document.getElementById('current-month-year').textContent = 
            `${year}年 ${monthNames[month]}`;
        
        // 获取当月第一天和最后一天
        const firstDay = new Date(year, month, 1);
        const lastDay = new Date(year, month + 1, 0);
        const startDay = firstDay.getDay(); // 0是星期天
        
        const calendarDays = document.getElementById('calendar-days');
        calendarDays.innerHTML = '';
        
        const today = new Date();
        
        // 添加上个月的最后几天
        for (let i = startDay - 1; i >= 0; i--) {
            const prevDate = new Date(year, month, -i);
            const dayElement = this.createDayElement(prevDate, true);
            calendarDays.appendChild(dayElement);
        }
        
        // 添加当月的天数
        for (let day = 1; day <= lastDay.getDate(); day++) {
            const date = new Date(year, month, day);
            const dayElement = this.createDayElement(date, false);
            
            // 标记今天
            if (date.toDateString() === today.toDateString()) {
                dayElement.classList.add('today');
            }
            
            calendarDays.appendChild(dayElement);
        }
        
        // 添加下个月的前几天
        const remainingDays = 42 - calendarDays.children.length; // 6行7列
        for (let day = 1; day <= remainingDays; day++) {
            const nextDate = new Date(year, month + 1, day);
            const dayElement = this.createDayElement(nextDate, true);
            calendarDays.appendChild(dayElement);
        }
    }
    
    // 创建日期元素
    createDayElement(date, isOtherMonth) {
        const dayElement = document.createElement('div');
        dayElement.className = 'calendar-day';
        dayElement.textContent = date.getDate();
        
        if (isOtherMonth) {
            dayElement.classList.add('other-month');
        }
        
        dayElement.addEventListener('click', () => {
            // 移除之前的选择
            document.querySelectorAll('.calendar-day.selected').forEach(el => {
                el.classList.remove('selected');
            });
            
            // 添加新的选择
            dayElement.classList.add('selected');
            this.selectedDate = date;
        });
        
        return dayElement;
    }
    
    // 初始化计时器
    initTimer() {
        this.updateTimerDisplay();
    }
    
    // 更新计时器显示
    updateTimerDisplay() {
        const minutes = String(this.timerMinutes).padStart(2, '0');
        const seconds = String(this.timerSeconds).padStart(2, '0');
        
        document.getElementById('timer-minutes').textContent = minutes;
        document.getElementById('timer-seconds').textContent = seconds;
    }
    
    // 开始计时器
    startTimer() {
        if (this.timerRunning) return;
        
        this.timerRunning = true;
        this.timerPaused = false;
        
        document.getElementById('timer-start').style.display = 'none';
        document.getElementById('timer-pause').style.display = 'inline-block';
        document.getElementById('timer-status').textContent = '专注中...保持专注！';
        
        this.timerInterval = setInterval(() => {
            if (this.timerSeconds === 0) {
                if (this.timerMinutes === 0) {
                    // 计时结束
                    this.timerComplete();
                    return;
                }
                this.timerMinutes--;
                this.timerSeconds = 59;
            } else {
                this.timerSeconds--;
            }
            
            this.updateTimerDisplay();
        }, 1000);
    }
    
    // 暂停计时器
    pauseTimer() {
        if (!this.timerRunning) return;
        
        this.timerRunning = false;
        this.timerPaused = true;
        
        clearInterval(this.timerInterval);
        
        document.getElementById('timer-start').style.display = 'inline-block';
        document.getElementById('timer-pause').style.display = 'none';
        document.getElementById('timer-status').textContent = '计时器已暂停';
    }
    
    // 重置计时器
    resetTimer() {
        this.timerRunning = false;
        this.timerPaused = false;
        
        clearInterval(this.timerInterval);
        
        // 重置为当前选择的时间
        const activePreset = document.querySelector('.preset-btn.active');
        this.timerMinutes = parseInt(activePreset.dataset.minutes);
        this.timerSeconds = 0;
        
        this.updateTimerDisplay();
        
        document.getElementById('timer-start').style.display = 'inline-block';
        document.getElementById('timer-pause').style.display = 'none';
        document.getElementById('timer-status').textContent = '准备开始专注时间';
    }
    
    // 计时完成
    timerComplete() {
        this.timerRunning = false;
        clearInterval(this.timerInterval);
        
        document.getElementById('timer-start').style.display = 'inline-block';
        document.getElementById('timer-pause').style.display = 'none';
        document.getElementById('timer-status').textContent = '🎉 专注时间完成！休息一下吧~';
        
        // 可以添加声音提醒或其他通知
        if ('Notification' in window && Notification.permission === 'granted') {
            new Notification('专注时间完成！', {
                body: '恭喜你完成了一次专注时间，休息一下吧！',
                icon: '/favicon.ico'
            });
        }
    }
    
    // 绑定事件
    bindEvents() {
        // 日历事件
        document.getElementById('prev-month').addEventListener('click', () => {
            this.currentDate.setMonth(this.currentDate.getMonth() - 1);
            this.updateCalendar();
        });
        
        document.getElementById('next-month').addEventListener('click', () => {
            this.currentDate.setMonth(this.currentDate.getMonth() + 1);
            this.updateCalendar();
        });
        
        // 计时器事件
        document.getElementById('timer-start').addEventListener('click', () => {
            this.startTimer();
        });
        
        document.getElementById('timer-pause').addEventListener('click', () => {
            this.pauseTimer();
        });
        
        document.getElementById('timer-reset').addEventListener('click', () => {
            this.resetTimer();
        });
        
        // 预设时间按钮
        document.querySelectorAll('.preset-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                if (this.timerRunning) return; // 运行中不允许切换
                
                // 更新激活状态
                document.querySelectorAll('.preset-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                
                // 设置时间
                this.timerMinutes = parseInt(btn.dataset.minutes);
                this.timerSeconds = 0;
                this.updateTimerDisplay();
            });
        });
        
        // 请求通知权限
        if ('Notification' in window && Notification.permission === 'default') {
            Notification.requestPermission();
        }
    }
}

// 当首页内容被激活时初始化
document.addEventListener('DOMContentLoaded', function() {
    let dashboard = null;
    
    // 监听菜单切换
    const menuItems = document.querySelectorAll('.submenu-item a');
    menuItems.forEach(item => {
        item.addEventListener('click', function() {
            const target = this.dataset.target;
            if (target === 'dashboard') {
                // 延迟初始化，确保DOM已渲染
                setTimeout(() => {
                    if (!dashboard) {
                        dashboard = new Dashboard();
                    }
                }, 100);
            }
        });
    });
    
    // 如果首页默认激活，立即初始化
    const activeMenuItem = document.querySelector('.submenu-item a.active');
    if (activeMenuItem && activeMenuItem.dataset.target === 'dashboard') {
        setTimeout(() => {
            dashboard = new Dashboard();
        }, 100);
    }
});
